package com.ljh.controller;

import com.ljh.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author LongJinHua
 * @date 2022-10-10
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private MongoTemplate mongoTemplate;

    // 增加用户
    @PostMapping("/add")
    public void addUser(@RequestBody User user) {
        mongoTemplate.save(user, "user");
        log.info("新增用户成功：" + user);
    }

    // 根据id删除用户
    @DeleteMapping("/delete/{id}")
    public void deleteUser(@PathVariable String id) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)), "user");
        log.info("删除用户成功：" + id);
    }

    // 更新用户信息
    @PutMapping("/update")
    public void updateUser(@RequestBody User user) {
        mongoTemplate.save(user, "user");
        log.info("更新用户信息成功：" + user);
    }

    // 根据id查询用户信息
    @GetMapping("/get/{id}")
    public User getUserById(@PathVariable String id) {
        return mongoTemplate.findById(id, User.class);
    }

    // 查询所有用户列表
    @GetMapping("/list")
    public List<User> getUsers() {
        return mongoTemplate.findAll(User.class);
    }
}
